import type { AppRoute } from '@jari-ace/app-bolts';

import type { RouteRecordStringComponent } from '@vben/types';

import { createAxios } from '@jari-ace/app-bolts';

type RouteRecord = RouteRecordStringComponent<string | undefined>;
const appName = import.meta.env.VITE_APP_NAME;
/**
 * 获取用户所有菜单
 */
export function getAllMenusApi(): Promise<RouteRecord[]> {
  const axios = createAxios();
  // 获取应用名 VITE_APP_NAME
  return new Promise((resolve, reject) => {
    axios
      .get<AppRoute[]>(`/routes/enabled/${appName}`)
      .then((res) => {
        const routes = buildMenuTree(res);
        resolve(routes); // 成功时解析数据
      })
      .catch((error) => {
        console.error('菜单获取失败', error);
        reject(error); // 失败时拒绝 Promise
      });
  });
}

/**
 * 根据route获取菜单项方法
 * @param route
 */
function getMenuByRoute(route: AppRoute): RouteRecord {
  return {
    path: route.path,
    name: route.name,
    component: route.component,
    meta: {
      title: route.title,
      icon: route.icon,
      activeIcon: route.activeIcon,
      activePath: route.activePath,
      affixTab: route.affixTab,
      affixTabOrder: route.affixTabOrder,
      order: route.order, // 排序值
      hideChildrenInMenu: route.hideChildrenInMenu, // 子菜单可见
      hideInBreadcrumb: route.hideInBreadcrumb, // 面包屑可见
      hideInMenu: route.hideInMenu, // 菜单可见
      hideInTab: route.hideInTab, // 标签页可见
      ignoreAccess: route.ignoreAccess, // 用于配置页面是否忽略权限，直接可以访问。
      keepAlive: route.keepAlive, // 不开启KeepAlive
      noBasicLayout: route.noBasicLayout, // 不使用基础布局
      openInNewWindow: route.openInNewWindow, // 设置为 true 时，会在新窗口打开页面。
      disabled: route.disabled, // 是否禁用
      addTo: route.addTo,
      badge: route.badge, // 徽标
      badgeType: route.badgeType, // 徽标类型
      badgeVariants: route.badgeVariants, // 徽标样式
      iframeSrc: route.iframeSrc, // iframe内嵌
      link: route.link, // 外链
      query: route.query, // 参数
    },
  };
}

/**
 * 解析菜单
 */
export function buildMenuTree(appRoutes: AppRoute[]): RouteRecord[] {
  // 遍历菜单递归出菜单树 递归方法
  function recursive(routes: AppRoute[], parentId?: string) {
    const menuTree: RouteRecord[] = [];
    routes.forEach((route) => {
      // parent不存在为根节点
      if ((!parentId && !route.parent) || route.parent?.id === parentId) {
        menuTree.push({
          ...getMenuByRoute(route),
          children: route.hasChildren ? recursive(routes, route.id) : [],
        });
      }
    });
    // 根据meta.order进行排序
    return menuTree.sort((a, b) => (a.meta?.order || 0) - (b.meta?.order || 0));
  }
  return recursive(appRoutes);
}
